<?php

namespace app\admin\model\note;

use think\Db;
use think\Model;


class Task extends Model
{

    

    

    // 表名
    protected $name = 'note_task';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

	public function day(array $tasks, $day){
		$dayWhere = [];
		if($day->uid != 0) $dayWhere['uid'] = $day->uid;
		if($day->contact_id != 0) $dayWhere['contact_id'] = $day->contact_id;
		$end_date = Day::where($dayWhere)->order('date_time desc')->value('date_text');

		$this->startTrans();
		try{
			foreach($tasks as &$value){
				if($value['content']!='') $value['content'] = addslashes($value['content']);

				if(isset($value['cycle_end_date']) && $value['cycle_end_date']!='') $end_date = $value['cycle_end_date'];
				if($value['content']=='' && $value['id']!=''){
					$where = ['cycle_day'=>['>=',$value['cycle_day']]];
					if($value['cycle_id'] == 0){
						$where['id|cycle_id'] = $value['id'];
					}else{
						$where['cycle_id'] = $value['cycle_id'];
					}
					// 删除任务
					$this->where($where)->delete();
				}else{
					if(!$value['id'] && $value['content']!=''){
						// 新增任务
						unset($value['id']);
						$value['day_id'] = $day->id;
						$value['uid'] = $day->uid;
						$value['customer_id'] = $day->customer_id;
						$value['contact_id'] = $day->contact_id;
						$value['create_time'] = time();
						$value['update_time'] = time();
						$task_id = $this->insertGetId($value);
					}else{
						// 修改任务
						$this->update($value,['id'=>$value['id']]);
						$task_id = $value['id'];
					}

					// 生成循环任务数据
					if($value['cycle']){
						$cycleText = $value['cycle'] == 4 ? 'Rem' : 'R';

						if($value['cycle_id'] == 0){
							if(!isset($value['id'])){
								// 新增任务
								$cycleIds = $this->getDateIds($dayWhere, $value, $day->date_text, $end_date);
								$cycleTasks = [];
								foreach($cycleIds as $k=>$day_id){
									$content = $value['content'] . '('.$cycleText.'.d'.($k+1).')';
									$cycleTasks[] = [
										'day_id' => $day_id,
										'uid' => $day->uid,
										'customer_id' => $day->customer_id,
										'contact_id' => $day->contact_id,
										'create_time' => time(),
										'update_time' => time(),
										'content' => $content,
										'cycle' => $value['cycle'],
										'cycle_id' => $task_id,
										'cycle_day' => $k+1,
										'cycle_days' => $value['cycle_days'],
										'cycle_end_date' => $value['cycle_end_date'],
									];
								}
								$this->saveAll($cycleTasks);
							}else{
								// 修改任务
								$this->update(['content' => Db::raw("CONCAT('{$value['content']}','($cycleText.d',cycle_day,')')")],['cycle_id' => $value['id']]);
//								$this->execute("UPDATE ".$this->getTable()." SET content=CONCAT('','',,')') WHERE cycle_id={$value['id']}");
							}
						}else{
							// 修改复习任务
							$content = explode('('.$cycleText.'.d', $value['content'])[0];
//							$this->where('id',$value['cycle_id'])->update(['content'=>$content]);
							$this->update(['content' => Db::raw("CONCAT('$content','($cycleText.d',cycle_day,')')")],['cycle_id' => $value['cycle_id'], 'cycle_day' => ['>',$value['cycle_day']]]);
//							$this->execute("UPDATE ".$this->getTable()." SET content=CONCAT('{$content}','(R.d',cycle_day,')') WHERE cycle_id={$value['cycle_id']} and cycle_day>{}");
						}
					}
				}
			}
			$this->commit();
			return true;
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
			return false;
		}
	}

	protected function timeWhile($start_date, $end_time, $days, $call_back){
		$dates = [];
		$i = 1;
		while(true){
			$time = strtotime($start_date.' +'.$i.' day');
			if($time <= $end_time){
				if(call_user_func($call_back,$time,explode(',',$days),$i)){
					$dates[] = date('Y-m-d',$time);
				}
			}else{
				break;
			}
			$i++;
		}
		return $dates;
	}

	protected function getCycleDates($task, $start_date, $end_date){
		switch($task['cycle']){
			// 每天
			case 1:
				$callback = function(){
					return true;
				};
				break;
			// 每周
			case 2:
				$callback = function($time,$days){
					return in_array(date('N', $time),$days);
				};
				break;
			// 每月
			case 3:
				$callback = function($time,$days){
					return in_array(date('j', $time),$days);
				};
				break;
			// ZH记忆曲线
			case 4:
				$callback = function($time,$days,$i){
					$days = [1,2,4,8,16,30,60,90];
					array_walk($days,function(&$v,$k){
//						$v -= 1;
					});
					return in_array($i,$days);
				};
				break;
			// 单次不循环
			default:
				$callback = function($time,$days){
					return false;
				};
		}
		$dates = $this->timeWhile($start_date, strtotime($end_date), $task['cycle_days'], $callback);
		return $dates;
	}

	protected function getDateIds($dayWhere, $task, $start_date, $end_date){
		$dates = $this->getCycleDates($task, $start_date, $end_date);
		$ids = Day::where($dayWhere)->where(['date_text' => ['in', $dates]])->column('id');
		return $ids;
	}

	protected function getContentAttr($value){
		return $value ? stripslashes($value) : '';
	}
}
